import Vue from 'vue'
import VueRouter from 'vue-router'

import CategoryPage from '@/views/layout/category.vue'
import HomePage from '@/views/layout/home.vue'
import UserPage from '@/views/layout/user.vue'
import CartPage from '@/views/layout/cart.vue'
import store from '@/store/index'
// 其余按需加载，加快打包速度
// 可以直接匹配到 login文件夹下的index.vue
const LoginIndex = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Search = () => import('@/views/search')
const MyOrder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const ProDetail = () => import('@/views/prodetail')
const SearchList = () => import('@/views/search/list.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/cart', component: CartPage },
      { path: '/category', component: CategoryPage },
      { path: '/home', component: HomePage },
      { path: '/user', component: UserPage }
    ]
  },
  { path: '/login', component: LoginIndex },
  { path: '/search', component: Search },
  { path: '/myorder', component: MyOrder },
  { path: '/pay', component: Pay },
  // 动态路由传参
  { path: '/proDetail/:goods_id', component: ProDetail },
  { path: '/searchlist', component: SearchList }
]

const router = new VueRouter({
  routes
})

// 权限页面路径
const authUrls = ['/pay', '/myorder']

// 路由全局前置守卫 所有路由在被真正访问到之前，都会先经过全局前置守卫
router.beforeEach((to, from, next) => {
  const token = store.getters.token
  console.log(to)
  console.log(from)
  console.log(next)
  console.log('登录验证', token)
  // 如果路径在权限页面中
  if (authUrls.includes(to.path) && !token) {
    console.log('rerer')
    console.log('测试git提交')
    router.push({ path: '/login' })

    return
  }
  next()
})

export default router
